import json,random
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from dj31.utils.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.views import View
# Create your views here.
from dj31.utils.yuntongxun.sms import CCP
from users.models import Users
from dj31.utils.response import res_json, Code, error_map

import logging
logger = logging.getLogger('django')


def hello(requset):

    return HttpResponse('hello word')


#图片验证码
def Image_code(request,img_id):
    text,image = captcha.generate_captcha() #获取列表的值
    redis_code = get_redis_connection('verify')
    # 保存     键   过期时间   值
    redis_code.setex('img_{}'.format(img_id).encode('utf8'),60,text)
    logger.info('图形验证码是:{}'.format(text))
    # request.session['image_code'] = text  # 设置键和值
    #过期时间
    # request.session.set_expiry(60)
    # print(request.session.keys())  #获取键
    # print(request.session.values())
    # print(request.session.get('image_code'))



# HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
    return HttpResponse(image,content_type='image/jpg')#'images/jpg'=下载

#用户名验证
class CheckUsernameView(View):
    '''
    验证用户名
    route : username/(?P<username>\w{5-20})/
    '''
    def get(self,request,username):
        '''
        统计数量
        :param username:
        :return: count  数量
        '''
        count = Users.objects.filter(username=username).count()
        data = {
            'count':count,
            'username':username,
        }

        return res_json(data=data)

    def post(self):
        pass

# 手机号验证
class CheckMobileView(View):
    '''
    验证手机号
    route : mobile/(?P<mobile>1[358]\d{9})/
    '''
    def get(self,request,mobile):
        '''
        统计数量
        :param mobile:
        :return: count  数量
        '''
        count = Users.objects.filter(mobile=mobile).count()
        data = {
            'count':count,
            'mobile':mobile,
        }

        return res_json(data=data)


    def post(self):
        pass

class SmsCodeView(View):
    # def get(self,request):
    #     pass
    def post(self,request):
        '''
        手机号 uuid图形验证码
        :param request:
        :return:
        '''
        #接收参数
        json_str = request.body
        '''
        mobile:
        text:
        image_code_id:
        '''
        if not json_str:
            return res_json(errno=Code.PARAMERR,errmsg='参数错误')  #4103
        dict_data = json.loads(json_str)
        image_code_client = dict_data.get('text')
        uuid = dict_data.get('image_code_id')
        mobile = dict_data.get('mobile')

        #参数的判断
        if not all([image_code_client,uuid,mobile]):
            return res_json(errno=Code.PARAMERR,errmsg='有参数缺失')

        #链接数据库
        redis_conn = get_redis_connection('verify')
        seng_flag = redis_conn.get('sms_flag_{}'.format(mobile))
        if seng_flag:
            return res_json(errno=Code.PARAMERR,errmsg='短信发送频繁')
        image_code_server = redis_conn.get('img_{}'.format(uuid))
        if image_code_server is None:
            return res_json(errno=Code.PARAMERR,errmsg=error_map[Code.PARAMERR])

        #删除数据库的验证码，防止重复测试
        try:
            redis_conn.delete('img_{}'.format(uuid))
        except Exception as e:
            logger.error(e)

        #比对
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():  #验证码进行变大写
            return res_json(errno=Code.PARAMERR,errmsg='图形验证码有误')

        #生成短信验证码
        sms_code = '%06d' %random.randint(0,999999)  #当数值不为6位数，补0
        #存到数据库，下一次使用
        #                  手机号设为id，300秒，值为短信验证码
        redis_conn.setex('sms_{}'.format(mobile),300,sms_code)

        #判断是否发送过
        redis_conn.setex('sms_flag_{}'.format(mobile),60,1)



        logger.info('短信验证码是:{}'.format(sms_code))
        logging.info('发送成功[手机号:{} 短信验证码:{}]'.format(mobile,sms_code))
        #调用接口发送短信
        # ccp = CCP()
        #                     手机号码 验证码  时间5分钟 模板1
        # ccp.send_template_sms(mobile,[sms_code,5],1)

        return res_json(errmsg='短信发送成功')


